import {
    WechatyBuilder,
    ScanStatus,
    log
} from 'wechaty';
import qrTerminal from 'qrcode-terminal';

import {
    defaultMessage,
    /* shardingMessage */
} from './sendMessage.js';

export class WechatBot {

    constructor() {
        this.bot = this.createBot();
        this.CHROME_BIN = process.env.CHROME_BIN ? {
            endpoint: process.env.CHROME_BIN
        } : {};
        this.serviceType = '';
    }

    // 扫码
    onScan = (qrcode, status) => {
        if (status === ScanStatus.Waiting || status === ScanStatus.Timeout) {
            // 在控制台显示二维码
            qrTerminal.generate(qrcode, {
                small: true
            });
            const qrcodeImageUrl = ['https://api.qrserver.com/v1/create-qr-code/?data=', encodeURIComponent(qrcode)].join('');
            console.log('onScan:', qrcodeImageUrl, ScanStatus[status], status);
        } else {
            log.info('onScan: %s(%s)', ScanStatus[status], status);
        }
    }

    // 登录
    onLogin = user => {
        console.log(`${user} has logged in`);
        const date = new Date();
        console.log(`Current time:${date}`);
        console.log(`Automatic robot chat mode has been activated`);
    }

    // 登出
    onLogout = user => {
        console.log(`${user} has logged out`);
    }

    // 收到好友请求
    onFriendShip = async friendship => {
        const frienddShipRe = /chatgpt|chat/;
        if (friendship.type() === 2) {
            if (frienddShipRe.test(friendship.hello())) {
                await friendship.accept();
            }
        }
    }

    // 消息发送
    onMessage = async msg => {
        // 默认消息回复
        await defaultMessage(msg, this.bot, this.serviceType);
        // 消息分片
        // await shardingMessage(msg, this.bot);
    }

    // 启动微信机器人
    start() {
        this.bot
            .start()
            .then(() => console.log('Start to log in wechat...'))
            .catch((e) => console.error('botStart error❌: ', e));
    }

    // 初始化机器人
    createBot() {
        const bot = WechatyBuilder.build({
            name: 'WechatEveryDay',
            puppet: 'wechaty-puppet-wechat4u', // 如果有token，记得更换对应的puppet
            // puppet: 'wechaty-puppet-wechat', // 如果 wechaty-puppet-wechat 存在问题，也可以尝试使用上面的 wechaty-puppet-wechat4u ，记得安装 wechaty-puppet-wechat4u
            puppetOptions: {
                uos: true,
                ...this.CHROME_BIN,
            }
        });
        // 扫码
        bot.on('scan', this.onScan);
        // 登录
        bot.on('login', this.onLogin);
        // 登出
        bot.on('logout', this.onLogout);
        // 收到消息
        bot.on('message', this.onMessage);
        // 添加好友
        bot.on('friendship', this.onFriendShip);
        // 错误
        bot.on('error', (e) => {
            console.error('bot error❌: ', e);
            console.log('❌ 程序退出,请重新运行程序');
            bot.stop();
            process.exit();
        });
        return bot;
    }
}